package cn.itcast.web.controller.cargo;

import cn.itcast.dao.cargo.ContractDao;
import cn.itcast.dao.system.UserDao;
import cn.itcast.domain.cargo.Contract;
import cn.itcast.domain.cargo.ContractExample;
import cn.itcast.domain.system.Dept;
import cn.itcast.domain.system.User;
import cn.itcast.service.cargo.ContractService;
import cn.itcast.service.system.DeptService;
import cn.itcast.service.system.UserService;
import cn.itcast.web.controller.BaseController;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/cargo/contract")
@Slf4j
public class ContractController extends BaseController{

    // 注入dubbo的服务接口的代理对象
    @Reference
    private ContractService contractService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private UserService userService;

    @Autowired
    private DeptService deptService;

    @Autowired
    private ContractDao contractDao;

    @Autowired
    private UserDao userDao;

    /**
     * 查询列表
     * ctrl + alt + o 导包、删除无用的包
     */
    @RequestMapping("/list")
    public String list(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "5") Integer pageSize) {
        log.info("执行用户分页的方法");

        // 构造查询对象
        ContractExample example = new ContractExample();
        // 根据create_time 创建时间，倒序排序
        example.setOrderByClause("create_time desc");
        // 条件集合
        ContractExample.Criteria criteria = example.createCriteria();
        // 添加查询条件：compnay_id
        criteria.andCompanyIdEqualTo(getLoginCompanyId());
        /**
         * 需求：细粒度的权限控制。不同的用户访问列表，看到的数据不一样
         * 用户的degree等级：
         *  0-saas管理员
         *  1-企业管理员
         *  2-管理所有下属部门和人员
         *  3-管理本部门
         *  4-普通员工
         */
        PageInfo<Contract> pageInfo = null;

        String checkState= null;

        // 获取登陆用户
        User loginUser = getLoginUser();
        Integer degree = loginUser.getDegree();
        if (degree == 4){
            //1. 普通用户登陆，查看购销合同，只能查看自己创建的购销合同
            //SELECT * FROM co_contract WHERE create_by='登陆用户的id'
            criteria.andCreateByEqualTo(loginUser.getId());
            pageInfo = contractService.findByPage(example, pageNum, pageSize);
        }
        else if (degree == 3) {
            //2. 部门经理登陆，可以查看自己部门下所有员工创建的购销合同
            //SELECT * FROM co_contract WHERE create_dept='登陆用户的id'
            criteria.andCreateDeptEqualTo(loginUser.getDeptId());
            pageInfo = contractService.findByPage(example, pageNum, pageSize);
            checkState= "审单人资格";
        } else if (degree == 2) {
            //3. 大部门经理登陆（有子孙部门），可以查看所有子孙部门创建的购销合同
            pageInfo  = contractService.findContractsByDeptId(loginUser.getDeptId(),pageNum,pageSize);
            checkState= "审单人资格";
        }

        // 存储查询结果
        request.setAttribute("pageInfo", pageInfo);

        if(checkState!=null){
            request.setAttribute("checkState",checkState);
        }

        return "cargo/contract/contract-list";
    }

    /**
     * 进入添加页面
     */
    @RequestMapping("/toAdd")
    public String toAdd() {

        //添加审单人（审单人必须是本部门的主管或者上级部门的主管）
        List<User> list = userService.findUserByDeptId(getLoginUser());
        request.setAttribute("list",list);

        return "cargo/contract/contract-add";
    }

    /**
     * 添加、修改
     */
    @RequestMapping("/edit")
    public String edit(Contract contract) {
        // 设置企业信息（先写死，后期从登陆用户动态获取）
        contract.setCompanyId(getLoginCompanyId());
        contract.setCompanyName(getLoginCompanyName());
        // 判断
        if (StringUtils.isEmpty(contract.getId())) {
            log.info("添加用户....");
            // 设置创建时间、创建人、创建人的部门
            contract.setCreateTime(new Date());
            contract.setCreateBy(getLoginUser().getId());
            contract.setCreateDept(getLoginUser().getDeptId());
            contractService.save(contract);
        } else {
            log.info("修改用户....");
            contractService.update(contract);
        }
        return "redirect:/cargo/contract/list";
    }

    /**
     * 进入修改页面
     */
    @RequestMapping("/toUpdate")
    public String toUpdate(String id) {
        // 根据id查询
        Contract contract = contractService.findById(id);
        // 保存
        request.setAttribute("contract", contract);

        //添加审单人（审单人必须是本部门的主管或者上级部门的主管）
        List<User> list = userService.findUserByDeptId(getLoginUser());
        request.setAttribute("list",list);
        return "cargo/contract/contract-update";
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public String delete(String id) {
        log.info("执行购销合同删除.....");
        Contract contract = contractService.findById(id);
        if(contract.getState()!=0){
            return "redirect:/cargo/contract/list";
        }
        contractService.delete(id);
        return "redirect:/cargo/contract/list";
    }

    /**
     * 购销合同列表，点击：查看、提交、取消
     * http://localhost:8080/cargo/contract/toView.do?id=6
     * http://localhost:8080/cargo/contract/submit.do?id=6
     * http://localhost:8080/cargo/contract/cancel.do?id=6
     */
    @RequestMapping("/toView")
    public String toView(String id) {
        log.info("执行购销合同查看.....");
        Contract contract = contractService.findById(id);
        request.setAttribute("contract",contract);
        return "cargo/contract/contract-view";
    }

    @RequestMapping("/submit")
    public String submit(String id) {
        log.info("执行购销合同提交.....");

        // 创建要更新的对象
        Contract contract = new Contract();
        // 设置更新条件
        contract.setId(id);
        // 设置更新的字段值: 提交，修改购销合同状态为1; 动态sql
        contract.setState(1);
        // 对象属性有值，才执行更新
        contractService.update(contract);
        User loginUser = (User) httpSession.getAttribute("loginUser");
        String deptId = loginUser.getDeptId();
        List <Dept>deptList=deptService.findParentName(deptId);
        request.setAttribute("deptList",deptList);
        return "redirect:/cargo/contract/list";
    }
    @RequestMapping("/cancel")
    public String cancel(String id) {
        log.info("执行购销合同提交.....");

        // 创建要更新的对象
        Contract contract = new Contract();
        // 设置更新条件
        contract.setId(id);
        // 设置更新的字段值: 取消，修改购销合同状态为0; 动态sql
        contract.setState(0);
        // 对象属性有值，才执行更新
        contractService.update(contract);
        return "redirect:/cargo/contract/list";
    }

    @RequestMapping("/check")
    public String check(Contract contract) {
        log.info("审核购销合同.....");
        contract.setState(2);
        contractService.update(contract);
        return "redirect:/cargo/contract/list";
    }

    @RequestMapping("/toCheck")
    public String toCheck(String id) {
        log.info("去审核页面.....");
        Contract contract = contractService.findById(id);

        String checkBy = contract.getCheckBy();


        request.setAttribute("contract",contract);
        return "cargo/contract/contract-check";
    }

    /**
     * 每天早上9点查一次船期，在船期三天前提醒
     */
    public void byShipTime() {

        //设置通知邮件
        Map<String, String> map = new HashMap<>();
        String title = "交货期限即将到期通知";
        String content = "交货期限即将截至，请及时确认船期与货物！如有特殊情况，请及时告知合作方并进行双方的协商沟通。";
        map.put("title", title);
        map.put("content", content);

        //获取三天内的毫秒数
        long timeZone = 60 * 1000 * 60 * 24 * 3;
        List<Contract> contractList = contractDao.selectByExample(new ContractExample());

        if (contractList != null && contractList.size() > 0) {
            for (Contract contract : contractList) {
                //获取相差的毫秒差
                long timePoint = contract.getShipTime().getTime() - System.currentTimeMillis();
                //判断是否到期，到期就发送邮件
                if (timePoint > 0 && timePoint < timeZone) {
                    User user = userDao.findById(contract.getCreateBy());
                    String email = user.getEmail();
                    if (email != null && !"".equals(email)) {
                        /*map.put("email",email);*/
                        map.put("email", "446307676@qq.com");//先写死方便测试*/
                        rabbitTemplate.convertAndSend("msg.email", map);
                    }
                }
            }
        }
    }
}











